package com.ble.juanyuan.blue20;


import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.*;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import com.ble.juanyuan.blue20.DeviceListActivity;

import java.io.*;
import java.util.UUID;

//import android.view.Menu;            //如使用菜单加入此三包
//import android.view.MenuInflater;
//import android.view.MenuItem;

public class BTClient extends Activity {

    private final static int REQUEST_CONNECT_DEVICE = 1;    //宏定义查询设备句柄
    private final static int REQUEST_OPEN_ADAPTER=2;

    private final static String MY_UUID = "00001101-0000-1000-8000-00805F9B34FB";   //SPP服务UUID号

    private InputStream is;    //输入流，用来接收蓝牙数据
    //private TextView text0;    //提示栏解句柄
    //private EditText edit0;    //发送数据输入句柄
    private TextView dis;       //接收数据显示句柄
    private ScrollView sv;      //翻页句柄
    private String smsg = "";    //显示用数据缓存
    private String fmsg = "";    //保存用数据缓存
    private byte[] recvbytes= new byte[7];//接收字节区

    TextView mConnectionState;
    EditText YN ;
    EditText EveryCircleCount ;
    CheckBox AutoCamera ;

    EditText XSpeed ;
    EditText YSpeed ;

    TextView Xangle;
    TextView Yangle;
    TextView WorkState;
    TextView SendView;
    TextView RecvView;

    private String filename=""; //用来保存存储的文件名
    private BluetoothDevice _device = null;     //蓝牙设备
    private BluetoothSocket _socket = null;      //蓝牙通信socket
    boolean _discoveryFinished = false;
    private boolean bRun = true;
    private boolean bThread = false;

    private BluetoothAdapter _bluetoothAdapter;    //获取本地蓝牙适配器，即蓝牙设备

    private static BluetoothAdapter getDefaultAdapter(Context context) {
        BluetoothAdapter adapter = null;
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            adapter = BluetoothAdapter.getDefaultAdapter();
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            final BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
            adapter = bluetoothManager.getAdapter();
        }
        return adapter;
    }


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);   //设置画面为主画面 main.xml

        //text0 = (TextView)findViewById(R.id.Text0);  //得到提示栏句柄
        //edit0 = (EditText)findViewById(R.id.Edit0);   //得到输入框句柄
        sv = (ScrollView)findViewById(R.id.ScrollView01);  //得到翻页句柄
        dis = (TextView) findViewById(R.id.in);      //得到数据显示句柄


        mConnectionState = (TextView) findViewById(R.id.connection_state);
        //mDataField = (TextView) findViewById(R.id.data_value);
        YN = (EditText) findViewById(R.id.YN);
        EveryCircleCount = (EditText) findViewById(R.id.EveryCircleCount);
        AutoCamera = (CheckBox) findViewById(R.id.AutoCamera);
        XSpeed = (EditText)findViewById(R.id.XSpeed);
        YSpeed = (EditText)findViewById(R.id.YSpeed);

        Xangle = (TextView)findViewById(R.id.Xangle);
        Yangle = (TextView)findViewById(R.id.Yangle);
        WorkState = (TextView)findViewById(R.id.Workstate);

        SendView = (TextView) findViewById(R.id.sendView);
        RecvView = (TextView) findViewById(R.id.recvView);
        _bluetoothAdapter = getDefaultAdapter(this);
        //如果打开本地蓝牙设备不成功，提示信息，结束程序
        if (_bluetoothAdapter == null){
            Toast.makeText(this, "无法打开手机蓝牙，请确认手机是否有蓝牙功能！", Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        // 设置设备可以被搜索
        new Thread(){
            public void run(){
                if(!_bluetoothAdapter.isEnabled()){
                    _bluetoothAdapter.enable();
                }
            }
        }.start();
    }

    //发送按键响应
    public void onSendButtonClicked(View v){
/*        int i=0;
        int n=0;
        try{
            OutputStream os = _socket.getOutputStream();   //蓝牙连接输出流
            byte[] bos = edit0.getText().toString().getBytes();
            for(i=0;i<bos.length;i++){
                if(bos[i]==0x0a)n++;
            }
            byte[] bos_new = new byte[bos.length+n];
            n=0;
            for(i=0;i<bos.length;i++){ //手机中换行为0a,将其改为0d 0a后再发送
                if(bos[i]==0x0a){
                    bos_new[n]=0x0d;
                    n++;
                    bos_new[n]=0x0a;
                }else{
                    bos_new[n]=bos[i];
                }
                n++;
            }

            os.write(bos_new);
        }catch(IOException e){
        }*/

        try {
            sendMsg(GenerateData());
        }
        catch (Exception ex)
        {
            Toast.makeText(this,ex.getMessage(),Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 显示状态 接收数据
     * @param xangle
     * @param yangle
     * @param worksstate
     */
    private void DisplayState(Integer xangle, Integer yangle, Boolean worksstate) {
        if (xangle!=null&& yangle!=null&&worksstate!=null) {
            Xangle.setText(xangle.toString());
            Yangle.setText(yangle.toString());
            WorkState.setText(worksstate ? R.string.Working : R.string.Stop);
        }
    }

    /**
     * 获取XY向速度 高字节位X向速度 低字节位Y向速度
     * @return
     */
    private byte GenerateXYSpeed(){
        byte Xbyte =Byte.parseByte(XSpeed.getText().toString());
        byte Ybyte =Byte.parseByte(YSpeed.getText().toString());
        byte XYSpeed = (byte)((Xbyte<<4)|Ybyte);
        return XYSpeed;
    }

    /**
     * s获取Y向角字节数据
     * @return 约定的格式排列
     */
    private byte[] GenerateY() {

        String[] YStr = YN.getText().toString().trim().replaceAll(" +", " ").split(" ");//字符数组 去掉多余空格

        byte[] tempY = new byte[YStr.length];
        for (int i=0;i<tempY.length;i++)
        {
            tempY[i] = (byte)Integer.parseInt(YStr[tempY.length-i-1]);
        }

        for (int i=0;i<tempY.length-1;i++)
        {
            tempY[i]-=tempY[i+1];
        }
        return tempY;
    }

    /**
     * 生成运行参数
     * @return
     */
    private byte[] GenerateData(){
        String[] YStr = YN.getText().toString().trim().split(" ");
        int bytes_length=YStr.length+7;//7个字节位固定位
        byte[] sendbytesData = new  byte[bytes_length];
        byte[] bytesY = GenerateY();//纵向角度 Yn

        //协议表约定
        sendbytesData[0]=(byte) 0xDD;//纵向角度结束符
        for (int i=0;i<bytesY.length;i++)
        {
            sendbytesData[i+1]=bytesY[i];
        }

        sendbytesData[bytesY.length+1]=GenerateXYSpeed();//高半字节为X向速度 低半字节为 Y向速度



        sendbytesData[bytesY.length+2]=Byte.parseByte(EveryCircleCount.getText().toString());//每圈拍照次数

        sendbytesData[bytesY.length+3]=(byte) 0xAA;//纵向角度结束位
        sendbytesData[bytesY.length+4]=(byte)0xBB;//纵向角度结束位
        sendbytesData[bytesY.length+5]=(byte) (AutoCamera.isChecked()?0x01:0x00);//自动拍照
        byte bt=0;
        for (int i=0;i<sendbytesData.length-1;i++)
        {
            bt+=sendbytesData[i];
        }
        sendbytesData[sendbytesData.length-1]=bt;//校验和


        return sendbytesData;
    }

    private void sendMsg(byte[] bytes){
        if (_socket!=null&&_socket.isConnected()) {
            try {
                OutputStream os = _socket.getOutputStream();   //蓝牙连接输出流
                os.write(bytes);
            } catch (IOException e) {
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
        else{
            Toast.makeText(this,"蓝牙未连接", Toast.LENGTH_SHORT).show();
        }


        SendView.setText(HexConvert.bytesToHexString(bytes));
    }
    /**
     * 发送控制命令
     * @param control 0 回原点 1 启动 2 停止
     */
    private void SendControl(int control)
    {
        /* 1  帧头  0xFF 2  帧头  0xEE  3    命令类型  1：回原点  2：启动 3：停止      4  校验和  前面 3 字节的校验和*/
        byte[] bytes = new byte[4];
        bytes[0]=(byte)0xFF;
        bytes[1]=(byte)0xEE;
        bytes[2]=(byte)control;
        int value =bytes[0]+bytes[1]+bytes[2];
        bytes[3] = (byte)(value%255);
        sendMsg(bytes);
    }

    //接收活动结果，响应 startActivityForResult()
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode){
            case REQUEST_CONNECT_DEVICE:     //连接结果，由DeviceListActivity设置返回
                // 响应返回结果
                if (resultCode == Activity.RESULT_OK) {   //连接成功，由DeviceListActivity设置返回
                    // MAC地址，由DeviceListActivity设置返回
                    String address = data.getExtras()
                            .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    // 得到蓝牙设备句柄
                    _device = _bluetoothAdapter.getRemoteDevice(address);

                    // 用服务号得到socket
                    try{
                        _socket = _device.createRfcommSocketToServiceRecord(UUID.fromString(MY_UUID));
                    }catch(IOException e){
                        Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
                    }
                    //连接socket
                    Button btn = (Button) findViewById(R.id.Button03);
                    try{
                        _socket.connect();
                        Toast.makeText(this, "连接"+_device.getName()+"成功！", Toast.LENGTH_SHORT).show();
                        mConnectionState.setText(R.string.connected);
                        btn.setText("断开");
                    }catch(IOException e){
                        try{
                            Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
                            _socket.close();
                            _socket = null;
                        }catch(IOException ee){
                            Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
                        }

                        return;
                    }

                    //打开接收线程
                    try{
                        is = _socket.getInputStream();   //得到蓝牙数据输入流
                    }catch(IOException e){
                        Toast.makeText(this, "接收数据失败！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if(!bThread){
                        ReadThread.start();
                        bThread=true;
                    }else{
                        bRun = true;
                    }
                }
                break;
            default:break;
        }
    }

    //接收数据线程
    Thread ReadThread=new Thread(){

        public void run(){
            int num = 0;

            int i = 0;
            int n = 0;
            bRun = true;
            //接收线程
            while(true){
                try{
                    while(is.available()==0){
                        while(!bRun){}
                    }
                    while(true){
                        num = is.read(recvbytes);         //读入数据
                        //n=0;

                        //String s0 = new String(buffer,0,num);


/*                        fmsg+=s0;    //保存收到数据
                        for(i=0;i<num;i++){
                            if((buffer[i] == 0x0d)&&(buffer[i+1]==0x0a)){
                                buffer_new[n] = 0x0a;
                                i++;
                            }else{
                                buffer_new[n] = buffer[i];
                            }
                            n++;
                        }
                        String s = new String(buffer_new,0,n);

                        //smsg+=s;   //写入接收缓存*/
                        if(is.available()==0)break;  //短时间没有数据才跳出进行显示
                    }
                    //发送显示消息，进行显示刷新
                    handler.sendMessage(handler.obtainMessage());
                }catch(IOException e){
                }
            }
        }
    };

    //消息处理队列
    Handler handler= new Handler(){
        public void handleMessage(Message msg){
            super.handleMessage(msg);
/*            dis.setText(smsg);   //显示数据
            sv.scrollTo(0,dis.getMeasuredHeight()); //跳至数据最后一页*/

            if (recvbytes[0]==(byte) 0xAA && recvbytes[1]==(byte) 0xBB)
            {
                Integer xangle = recvbytes[2]>0 ? recvbytes[3]+0xFF : recvbytes[3];
                Integer yangle = new Integer(recvbytes[4]&0xFF);
                Boolean worksstate = recvbytes[5]>0?true:false;

                DisplayState(xangle, yangle, worksstate);

                RecvView.setText(HexConvert.bytesToHexString(recvbytes));
            }
        }
    };

    //关闭程序掉用处理部分
    public void onDestroy(){
        super.onDestroy();
        if(_socket!=null)  //关闭连接socket
            try{
                _socket.close();
            }catch(IOException e){}
        //	_bluetooth.disable();  //关闭蓝牙服务
    }

    //菜单处理部分
  /* @Override
    public boolean onCreateOptionsMenu(Menu menu) {//建立菜单
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_menu, menu);
        return true;
    }*/

  /*  @Override
    public boolean onOptionsItemSelected(MenuItem item) { //菜单响应函数
        switch (item.getItemId()) {
        case R.id.scan:
        	if(_bluetooth.isEnabled()==false){
        		Toast.makeText(this, "Open BT......", Toast.LENGTH_LONG).show();
        		return true;
        	}
            // Launch the DeviceListActivity to see devices and do scan
            Intent serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
            return true;
        case R.id.quit:
            finish();
            return true;
        case R.id.clear:
        	smsg="";
        	ls.setText(smsg);
        	return true;
        case R.id.save:
        	Save();
        	return true;
        }
        return false;
    }*/

    //连接按键响应函数
    public void onConnectButtonClicked(View v){
        if(!_bluetoothAdapter.isEnabled()){  //如果蓝牙服务不可用则提示
            Toast.makeText(this, " 打开蓝牙中...", Toast.LENGTH_LONG).show();
            return;
        }


        //如未连接设备则打开DeviceListActivity进行设备搜索
        Button btn = (Button) findViewById(R.id.Button03);
        if(_socket==null){
            Intent serverIntent = new Intent(this, DeviceListActivity.class); //跳转程序设置
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);  //设置返回宏定义
        }
        else{
            //关闭连接socket
            try{

                is.close();
                _socket.close();
                _socket = null;
                bRun = false;
                btn.setText("连接");
            }catch(IOException e){}
        }
    }

/*    //保存按键响应函数
    public void onSaveButtonClicked(View v){
        Save();
    }*/

    //清除按键响应函数
    public void onClearButtonClicked(View v){
        smsg="";
        fmsg="";
        dis.setText(smsg);
    }

    //退出按键响应函数
    public void onQuitButtonClicked(View v){
        finish();
    }

    //开启
    public void onStart(View view){
        SendControl(2);
    }

    //停止
    public  void  onStop(View view){
        SendControl(3);
    }

    //复位
    public void onReset(View view){
        SendControl(1);
    }
/*    //保存功能实现
    private void Save() {
        //显示对话框输入文件名
        LayoutInflater factory = LayoutInflater.from(BTClient.this);  //图层模板生成器句柄
        final View DialogView =  factory.inflate(R.layout.sname, null);  //用sname.xml模板生成视图模板
        new AlertDialog.Builder(BTClient.this)
                .setTitle("文件名")
                .setView(DialogView)   //设置视图模板
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() //确定按键响应函数
                        {
                            public void onClick(DialogInterface dialog, int whichButton){
                                EditText text1 = (EditText)DialogView.findViewById(R.id.sname);  //得到文件名输入框句柄
                                filename = text1.getText().toString();  //得到文件名

                                try{
                                    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){  //如果SD卡已准备好

                                        filename =filename+".txt";   //在文件名末尾加上.txt
                                        File sdCardDir = Environment.getExternalStorageDirectory();  //得到SD卡根目录
                                        File BuildDir = new File(sdCardDir, "/data");   //打开data目录，如不存在则生成
                                        if(BuildDir.exists()==false)BuildDir.mkdirs();
                                        File saveFile =new File(BuildDir, filename);  //新建文件句柄，如已存在仍新建文档
                                        FileOutputStream stream = new FileOutputStream(saveFile);  //打开文件输入流
                                        stream.write(fmsg.getBytes());
                                        stream.close();
                                        Toast.makeText(BTClient.this, "存储成功！", Toast.LENGTH_SHORT).show();
                                    }else{
                                        Toast.makeText(BTClient.this, "没有存储卡！", Toast.LENGTH_LONG).show();
                                    }

                                }catch(IOException e){
                                    return;
                                }



                            }
                        })
                .setNegativeButton("取消",   //取消按键响应函数,直接退出对话框不做任何处理
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).show();  //显示对话框
    }*/
}
